package com.zuoyy.common.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

/**
 * Created by maqian on 2018/12/20.
 * 导出excel小工具
 */
public class ExportKit {

    private PrintWriter writer;

    public ExportKit(HttpServletResponse response, String filename) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".csv");
        response.setContentType("application/octet-stream");
        response.getOutputStream().write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
        this.writer = new PrintWriter(response.getOutputStream());
    }

    public void println(List<?> data) {
        ExportKit.println(writer, data);
    }

    public void close() {
        writer.flush();
        writer.close();
    }

    public static void println(PrintWriter writer, List<?> data) {
        StringBuilder sb = new StringBuilder(data.size() * 15);
        for (Iterator<?> iterator = data.iterator(); iterator.hasNext(); ) {
            Object datum = iterator.next();
            if (datum == null) {
                datum = "";
            }

            sb.append("\"" + datum.toString().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "") + "\"");
            if (iterator.hasNext()) {
                sb.append(",");
            }
        }
        writer.println(sb);
    }

}
